package com.hbisedm.interninfosys.intern.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.entity.vo.TemplateWordConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.WordImageEntity;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbisedm.interninfosys.commonutils.R;
import com.hbisedm.interninfosys.intern.entity.MsgClient;
import com.hbisedm.interninfosys.intern.entity.MsgClientGroup;
import com.hbisedm.interninfosys.intern.entity.StuInternship;
import com.hbisedm.interninfosys.intern.entity.TestPoiWord;
import com.hbisedm.interninfosys.intern.entity.vo.ExcelInternshipVo;
import com.hbisedm.interninfosys.intern.entity.vo.ExcelPersonVo;
import com.hbisedm.interninfosys.intern.service.IInternshipInfoService;
import com.hbisedm.interninfosys.intern.service.IStuInternshipService;
import com.hbisedm.interninfosys.intern.service.IUserRoleService;
import com.hbisedm.interninfosys.intern.service.IUserService;
import com.hbisedm.interninfosys.listener.ExcelInternshipListener;
import com.hbisedm.interninfosys.listener.ExcelListener;
import com.hbisedm.interninfosys.utils.AliyunOssUtil;
import com.hbisedm.interninfosys.utils.TransUtils;
import lombok.SneakyThrows;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping("EasypoiSingleExcelViewTest")
public class ExcelToHtmlController {

    @Autowired
    private AliyunOssUtil ossUtil;

    @Autowired
    private AliyunOssUtil aliyunOssUtil;

    @Autowired
    private IStuInternshipService stuInternshipService;

    @RequestMapping("/test1")
    public String download(ModelMap map) {
        List<MsgClient> list = new ArrayList<MsgClient>();
        for (int i = 0; i < 100; i++) {
            MsgClient client = new MsgClient();
            client.setBirthday(new Date());
            client.setClientName("小明" + i);
            client.setClientPhone("18797" + i);
            client.setCreateBy("JueYue");
            client.setId("1" + i);
            client.setRemark("测试" + i);
            MsgClientGroup group = new MsgClientGroup();
            group.setGroupName("测试" + i);
            client.setGroup(group);
            list.add(client);
        }
        ExportParams params = new ExportParams("2412312", "测试", ExcelType.XSSF);
        params.setFreezeCol(2);
        map.put(NormalExcelConstants.DATA_LIST, list);
        map.put(NormalExcelConstants.CLASS, MsgClient.class);
        map.put(NormalExcelConstants.PARAMS, params);
        return NormalExcelConstants.EASYPOI_EXCEL_VIEW;

    }


    @SneakyThrows
    @RequestMapping("/test")
    public void download01(ModelMap modelMap, HttpServletRequest request,
                           HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        String url = "exceltohtml/UnitForm.docx";
        TemplateExportParams params = new TemplateExportParams(url);
        List<TestPoiWord> list = new ArrayList<TestPoiWord>();

        TestPoiWord student = new TestPoiWord();
        student.setDepartment("XX部");
        student.setGrade("11");
        student.setInternshipDate("2020-11-01");
        student.setInternshipUnit("XXXXXX");
        student.setMajor("XXX专业");
        student.setStudentName("Hbisedm");
        student.setStudentNo("17400000");
        list.add(student);
        map.put("entity", student);

        WordImageEntity companyImg = new WordImageEntity();
        companyImg.setHeight(100);
        companyImg.setWidth(100);
        companyImg.setType(WordImageEntity.Data);
        companyImg.setData(TransUtils.image2byte("https://hbisedm-oss.oss-cn-hangzhou.aliyuncs.com/image/company.jpg"));
        map.put("companyImg", companyImg);

        WordImageEntity teacherImg = new WordImageEntity();
        teacherImg.setHeight(50);
        teacherImg.setWidth(100);
        teacherImg.setType(WordImageEntity.Data);
        teacherImg.setData(TransUtils.image2byte("https://hbisedm-oss.oss-cn-hangzhou.aliyuncs.com/image/teacher.jpg"));
        map.put("teacherImg", teacherImg);

        modelMap.put(TemplateWordConstants.FILE_NAME, "实习信息");
        modelMap.put(TemplateWordConstants.PARAMS, params);
        modelMap.put(TemplateWordConstants.MAP_DATA, map);
        modelMap.put(TemplateWordConstants.URL, url);
//        PoiBaseView.render(modelMap, request, response,
//                TemplateWordConstants.EASYPOI_TEMPLATE_WORD_VIEW);
        try {
            renderMergedOutputModel(modelMap, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String codedFileName = "临时文件.docx";
        if (model.containsKey("fileName")) {
            codedFileName = (String)model.get("fileName") + ".docx";
        }
        codedFileName = URLEncoder.encode(codedFileName, "UTF8");
        response.setHeader("content-disposition", "attachment;filename=" + codedFileName);
        XWPFDocument document = WordExportUtil.exportWord07((String)model.get("url"), (Map)model.get("map"));

        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream out = response.getOutputStream();
        document.write(out);
        out.flush();
    }


    /**
     * 测试用，实际没用
     * @return
     * @throws Exception
     */
    @GetMapping("/downloadFile")
    public ResponseEntity<FileSystemResource> downloadFile() throws Exception {

        //获得完整的路径
        String path="D://file//temp.pdf";

        //输出路径
        System.out.println("path:"+path);

        File file = new File(path);
        System.out.println("fileName:"+file.getName());
        //处理文件名中文编码
        String myFileName= URLEncoder.encode(file.getName(), "utf-8");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + myFileName);
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));

    }


    @PostMapping("/uploadFile")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file != null) {
                String fileName = file.getOriginalFilename();
                if (!"".equals(fileName.trim())) {
                    File newFile = new File(fileName);

                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();

                    //把file里的内容复制到newFile中
                    file.transferTo(newFile);

                    String upload = ossUtil.upload(newFile);

                    //图片回显地址:
                    //http://yiyige.oss-cn-hangzhou.aliyuncs.com/images/2019-10-21/6c964702b67d4eeb920e7f1f4358189b-dishu.jpg
                    System.out.println("path=" + upload);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "success";
    }


    /**
     * 预览接收函PDF接口
     * @param request
     * @param response
     * @param sid
     * @param iid
     */
    @RequestMapping(value = "/preview/{sid}/{iid}", method = RequestMethod.GET)
    public void pdfStreamHandler(HttpServletRequest request,
                                 HttpServletResponse response,
                                 @PathVariable String sid,
                                 @PathVariable String iid) {
        System.out.println("sid => " + sid);
        System.out.println("iid => " + iid);

        /**
         *
         * 将获取对应的stuinternship对象 （这时候的对象 是有pdfPath的）
         * 将aliyunOssUtil.getFile 第一个参数替换成pdfPath
         *
         */

        StuInternship internship = stuInternshipService.getBaseMapper().selectOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, sid).eq(StuInternship::getIid, iid));
        String unitLetterPdfPath = internship.getUnitLetterPdfPath();

        //todo 将路径配置到 application.yml
        String localFile = "D:\\file\\temp.pdf";

        aliyunOssUtil.getFile(unitLetterPdfPath, localFile);

        //PDF文件地址
        File file = new File(localFile);
        if (file.exists()) {
            byte[] data = null;
            InputStream input=null;
            try {
                input= new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);

                response.getOutputStream().write(data);
            } catch (Exception e) {
                System.out.println("pdf文件处理异常：" + e);
            }finally{
                try {
                    if(input!=null){
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 预览鉴定表PDF接口
     * @param request
     * @param response
     * @param sid
     * @param iid
     */
    @RequestMapping(value = "/internshipPreview/{sid}/{iid}", method = RequestMethod.GET)
    public void internshipPreview(HttpServletRequest request,
                                 HttpServletResponse response,
                                 @PathVariable String sid,
                                 @PathVariable String iid) {
        System.out.println("sid => " + sid);
        System.out.println("iid => " + iid);

        /**
         *
         * 将获取对应的stuinternship对象 （这时候的对象 是有pdfPath的）
         * 将aliyunOssUtil.getFile 第一个参数替换成pdfPath
         *
         */

        StuInternship internship = stuInternshipService.getBaseMapper().selectOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, sid).eq(StuInternship::getIid, iid));
        String unitLetterPdfPath = internship.getInternFormPdfPath();

        //todo 将路径配置到 application.yml
        String localFile = "D:\\file\\temp.pdf";

        aliyunOssUtil.getFile(unitLetterPdfPath, localFile);

        //PDF文件地址
        File file = new File(localFile);
        if (file.exists()) {
            byte[] data = null;
            InputStream input=null;
            try {
                input= new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);

                response.getOutputStream().write(data);
            } catch (Exception e) {
                System.out.println("pdf文件处理异常：" + e);
            }finally{
                try {
                    if(input!=null){
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Autowired
    private IUserService userService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private IInternshipInfoService internshipInfoService;

    @Autowired
    private IUserRoleService userRoleService;

    /**
     * 导入学生或教师的excel到数据库
     * @param file
     * @param type
     * @return
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("/importExcelTest")
    public R importExcelTest(@RequestParam("file") MultipartFile file, @RequestParam("type") Integer type) throws  IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader excelReader  = EasyExcel.read(inputStream, ExcelPersonVo.class, new ExcelListener(userService, userRoleService, bCryptPasswordEncoder, type)).build();
        ReadSheet readSheet = EasyExcel.readSheet(0).build();

        excelReader.read(readSheet);
        // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
        excelReader.finish();

        return R.ok();
    }

    /**
     * 导入企业的excel到数据库
     * @param file
     * @return
     * @throws IOException
     */

    @ResponseBody
    @PostMapping("/importExcelInternship")
    public R importExcelInternship(@RequestParam("file") MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader excelReader  = EasyExcel.read(inputStream, ExcelInternshipVo.class, new ExcelInternshipListener(bCryptPasswordEncoder, userService,userRoleService, internshipInfoService)).build();
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        excelReader.read(readSheet);
        // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
        excelReader.finish();
        return R.ok();
    }
}
